package com.dd.ms.auth.config.auth;

import com.dd.ms.auth.service.impl.TokenBlacklistService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author liuxianmeng
 * @CreateTime 2025/7/8 16:01
 * @Description JWT认证过滤器 - 处理每个请求的认证流程
 *
 * 工作流程：
 * 1. 从Authorization头提取JWT令牌
 * 2. 验证令牌有效性
 * 3. 解析令牌中的用户信息和角色
 * 4. 创建Authentication对象并存入安全上下文
 * 5. 继续过滤器链
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private static final String AUTH_HEADER_PREFIX = "Bearer ";
    private final JwtUtils jwtUtils;
    private final TokenBlacklistService tokenBlacklistService;

    // 常量定义排除路径（与 SecurityConfig 共享）
    public static final List<String> EXCLUDED_PATHS = Arrays.asList(
            "/auth/gene-secret-key",
            "/auth/register",
            "/auth/login"
    );

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        return EXCLUDED_PATHS.stream()
                .anyMatch(path -> new AntPathRequestMatcher(path).matches(request));
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        // 清理 SecurityContext，确保每个请求独立
        SecurityContextHolder.clearContext();

        String token = extractToken(request);
        if (token == null) {
            filterChain.doFilter(request, response); // 无 Token 继续链
            return;
        }

        try {
            if (tokenBlacklistService.isTokenRevoked(token)) {
                log.warn("Token revoked: {}", token);
                sendJsonError(response, HttpServletResponse.SC_UNAUTHORIZED, "Token revoked");
                return;
            }

            Claims claims = jwtUtils.parseToken(token);
            String username = claims.getSubject();
            @SuppressWarnings("unchecked")
            List<String> roleList = (List<String>) claims.get("roles");

            if (SecurityContextHolder.getContext().getAuthentication() == null) {
                // 直接传入List<String>
                List<SimpleGrantedAuthority> authorities = parseRoles(roleList);
                UsernamePasswordAuthenticationToken authToken =
                        new UsernamePasswordAuthenticationToken(username, null, authorities);
                authToken.setDetails(new JwtAuthenticationDetails(claims));
                SecurityContextHolder.getContext().setAuthentication(authToken);
            }
        } catch (JwtException | IllegalArgumentException e) {
            log.error("JWT validation failed: {}", e.getMessage());
            sendJsonError(response, HttpServletResponse.SC_UNAUTHORIZED, "Invalid JWT token");
            return;
        }

        filterChain.doFilter(request, response);
    }

    private void sendJsonError(HttpServletResponse response, int status, String message) throws IOException {
        response.setStatus(status);
        response.setContentType("application/json");
        response.getWriter().write("{\"error\": \"" + message + "\"}");
    }

    private String extractToken(HttpServletRequest request) {
        String header = request.getHeader("Authorization");
        if (header != null && header.startsWith(AUTH_HEADER_PREFIX)) {
            return header.substring(AUTH_HEADER_PREFIX.length());
        }
        return null;
    }

    /**
     * 将角色列表转换为Spring Security的权限对象
     *
     * @param roleList 角色字符串列表（直接从JWT Claims获取）
     * @return List<SimpleGrantedAuthority> 权限集合
     */
    private List<SimpleGrantedAuthority> parseRoles(List<String> roleList) {
        if (roleList == null || roleList.isEmpty()) {
            return Collections.emptyList();
        }

        return roleList.stream()
                .filter(role -> !role.trim().isEmpty())
                .map(role -> "ROLE_" + role) // 添加Spring Security要求的前缀
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }

    // JWT认证详情对象
    public static class JwtAuthenticationDetails {
        private final Map<String, Object> claims;

        public JwtAuthenticationDetails(Claims claims) {
            this.claims = new HashMap<>();
            this.claims.putAll(claims);
        }

        public <T> T getClaim(String name, Class<T> type) {
            return claims.get(name) != null ? type.cast(claims.get(name)) : null;
        }
    }
}